﻿using Coder.Configs;
using Coder.Entity;
using Egg;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;

namespace ModularCenter
{
    public partial class DigEntities : Form
    {
        private readonly List<Table> _tables;
        private readonly List<string> _paths;
        private readonly FrmParent _frmParent;

        /// <summary>
        /// 表定义
        /// </summary>
        public Table? Table { get; private set; }

        /// <summary>
        /// 路径
        /// </summary>
        public string? Path { get; private set; }

        /// <summary>
        /// 实例选择窗口
        /// </summary>
        /// <param name="frmParent"></param>
        public DigEntities(FrmParent frmParent)
        {
            _tables = new List<Table>();
            _paths = new List<string>();
            _frmParent = frmParent;
            InitializeComponent();
        }

        // 加载配置
        private void LoadConfigs(string path, string? rootPath = null)
        {
            if (rootPath is null) rootPath = path;
            var files = egg.IO.GetFiles(path, "*.json");
            foreach (var file in files)
            {
                string absPath = file.Substring(rootPath.Length);
                _paths.Add(absPath);
                _tables.Add(Table.LoadFromFile(file, false));
            }
            var dirs = egg.IO.GetFolders(path);
            foreach (var dir in dirs)
            {
                LoadConfigs(dir, rootPath);
            }
        }

        private void Reload()
        {
            // 重新获取所有配置
            _tables.Clear();
            this.LoadConfigs(egg.IO.GetClosedPath(_frmParent.WorkFolder) + Config.DIR_ENTITIES);
            // 刷新列表
            this.listView1.Items.Clear();
            foreach (var table in _tables)
            {
                ListViewItem item = new ListViewItem(table.Properties.VarName);
                //item.SubItems.Add(table.Properties.VarName);
                item.SubItems.Add(table.Properties.Text);
                item.ImageIndex = 0;
                this.listView1.Items.Add(item);
            }
        }

        private void FrmEntity_Load(object sender, EventArgs e)
        {
            this.Text = $"选择实例";
            this.Reload();
        }

        private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.listView1.SelectedIndices.Count <= 0) return;
            int index = this.listView1.SelectedIndices[0];
            this.Table = _tables[index];
            this.Path = _paths[index];
            this.DialogResult = DialogResult.OK;
        }
    }
}
